#include "luaengine.h"
#include <QString>
#include <QDir>
#include <QFileInfo>
#include <QFile>

#include <QDebug>

#define PLUGINS_PATH    "./plugins/lua"

LuaEngine *LuaEngine::_instance = nullptr;

#include <glib.h>
#include "tvbuff.h"
#include "tvbuff-int.h"
#include "packet.h"
#include "proto.h"

#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */

void recent_init(void);
extern void pilua_init(void *client_data);
extern void pilua_early_cleanup(void);
extern void pilua_cleanup(void);
extern void pilua_reload_plugins(void *client_data);

#ifdef __cplusplus
}
#endif /* __cplusplus */

LuaEngine::LuaEngine()
{

}

LuaEngine::~LuaEngine()
{
    proto_cleanup();
    pilua_cleanup();
}

void LuaEngine::loadAllPlugins()
{
    recent_init();
    packet_init();
    proto_init(NULL, NULL);
    pilua_init(nullptr);fflush(stdout);
}

void LuaEngine::reloadLuaPlugins()
{
    pilua_reload_plugins(nullptr);fflush(stdout);
}

void LuaEngine::tryAllProtocols()
{
    tvbuff_t *tvb = NULL;
    packet_info *pinfo = NULL;
    proto_tree *tree = NULL;
    uint8_t *data;

    GList *dissector_names = get_dissector_names();

    if (dissector_names == nullptr) return;

    pinfo = (packet_info *)calloc(1, sizeof(packet_info));
    pinfo->proto_name = "<Missing Protocol Name>";
    pinfo->presence_flags = 0;
    pinfo->num = 0;


    tree = proto_tree_create_root(pinfo);
    proto_tree_set_visible(tree, false);

    data = (uint8_t *)malloc(256);
    snprintf((char*)data, 256, "%s", "hello lua.68656C6C6F206C75612E");
    tvb = tvb_new_real_data(data, strlen((char*)data), strlen((char*)data));
    tvb_set_free_cb(tvb, free);

    add_new_data_source(pinfo, tvb, "Frame");
    for (GList *l = dissector_names; l != NULL; l = l->next) {
        dissector_handle_t handle = find_dissector((const char *)l->data);
        call_dissector(handle, tvb, pinfo, tree);fflush(stdout);
    }
    free(tree);
    tvb_free(tvb);
}
